#include "TcpServer.h"



class EchoServer{

public:
    EchoServer(EventLoop* loop, const InetAddress& addr, const std::string &name, int threadNum)
        : loop_(loop), server_(loop, addr, name)
        {

            // 线程数
            server_.setThreadNum(threadNum);
            // 回调函数
            server_.setConnectionCallback([](const TcpConnectionPtr& ptr) -> void{
                // 连接或者断开连接都会执行
                
                LOG_INFO("connect %s : %s ", ptr->connected()? "up" : "down", ptr->peerAddr().toIpPort().c_str());                
            });

            server_.setMessageCallback([](const TcpConnectionPtr& ptr, Buffer &buff, Timestamp Timestamp) -> void{
                LOG_INFO("start message callback");
                std::string msg = buff.retrieveAllAsString();
                if (!msg.empty()) {
                    LOG_INFO("recv ipport: %s . meesage : %s", ptr->peerAddr().toIpPort().c_str(), msg.c_str());
                    ptr->send(msg);
                    LOG_INFO("send to ipport: %s . meesage : %s", ptr->peerAddr().toIpPort().c_str(), msg.c_str());
                    // 不要在这里 shutdown
                } else {
                    // 客户端关闭写端，服务端应关闭连接
                    LOG_INFO("peer closed, shutdown connection");
                    ptr->shutdown();
                }

            });

            

        }

    void start(){
        server_.start();
    }


private:
    EventLoop *loop_; // baseLoop
    TcpServer server_;
};

int main(){
    EventLoop baseLoop;
    InetAddress addr(8080, "127.0.0.1");
    EchoServer server(&baseLoop, addr, "server_d", 2);
    server.start();
    baseLoop.loop();


    return 0;
}